<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page isELIgnored="false" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的购物车</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f5f5f5;
            color: #333;
            padding: 20px;
        }

        .cart-container {
            max-width: 1200px;
            margin: 0 auto;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            padding: 20px;
        }

        .cart-header {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
            font-weight: bold;
        }

        .cart-header .select-all {
            display: flex;
            align-items: center;
            width: 120px;
        }

        .cart-header .select-all input {
            margin-right: 8px;
            cursor: pointer;
        }

        .cart-header .product-info {
            flex: 3;
        }

        .cart-header .price,
        .cart-header .quantity,
        .cart-header .subtotal,
        .cart-header .action {
            flex: 1;
            text-align: center;
        }

        .cart-item {
            display: flex;
            align-items: center;
            padding: 20px 0;
            border-bottom: 1px solid #eee;
        }

        .cart-item .item-select {
            width: 120px;
            display: flex;
            justify-content: center;
        }

        .cart-item .item-select input {
            cursor: pointer;
        }

        .cart-item .item-info {
            flex: 3;
            display: flex;
            align-items: center;
        }

        .cart-item .item-img {
            width: 80px;
            height: 80px;
            margin-right: 15px;
            border-radius: 4px;
            overflow: hidden;
        }

        .cart-item .item-img img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .cart-item .item-name {
            font-size: 16px;
        }

        .cart-item .item-spec {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        .cart-item .item-price,
        .cart-item .item-quantity,
        .cart-item .item-subtotal {
            flex: 1;
            text-align: center;
        }

        .cart-item .item-price {
            color: #e4393c;
            font-weight: bold;
        }

        .cart-item .item-quantity {
            display: flex;
            justify-content: center;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .quantity-btn {
            width: 30px;
            height: 30px;
            background: #f5f5f5;
            border: none;
            font-size: 16px;
            cursor: pointer;
        }

        .quantity-input {
            width: 50px;
            height: 30px;
            text-align: center;
            border: none;
            border-left: 1px solid #ddd;
            border-right: 1px solid #ddd;
        }

        .cart-item .item-action {
            flex: 1;
            text-align: center;
        }

        .item-action .delete-btn {
            color: #999;
            cursor: pointer;
        }

        .item-action .delete-btn:hover {
            color: #e4393c;
        }

        .cart-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 0;
            margin-top: 20px;
        }

        .cart-footer .continue-shopping {
            color: #666;
            cursor: pointer;
        }

        .cart-footer .total-box {
            display: flex;
            align-items: center;
        }

        .total-info {
            text-align: right;
            margin-right: 30px;
        }

        .total-info .total-amount {
            font-size: 18px;
            color: #e4393c;
            font-weight: bold;
            margin-top: 5px;
        }

        .checkout-btn {
            background: #e4393c;
            color: white;
            border: none;
            padding: 12px 40px;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .checkout-btn:hover {
            background: #c91623;
        }

        .checkout-btn.disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .empty-cart {
            text-align: center;
            padding: 50px 0;
            color: #999;
        }

        .empty-cart img {
            width: 120px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div class="cart-container">
    <div class="cart-header">
        <div class="select-all">
            <input type="checkbox" id="select-all"> 全选
        </div>
        <div class="product-info">商品信息</div>
        <div class="price">单价</div>
        <div class="subtotal">小计</div>
        <div class="action">操作</div>
    </div>

    <!-- 购物车商品列表 -->
    ${shopCar.size()}
    <c:choose>

        <c:when test="${not empty shopCar && shopCar.size() > 0}">
            <c:forEach items="${shopCar}" var="item">
                <div class="cart-item" data-id="${item.shopid}">
                    <div class="item-select">
                        <input type="checkbox" class="item-check" ${item.selected ? 'checked' : ''}>
                    </div>
                    <div class="item-info">
                        <div class="item-img">
                            <img src="${item.img}" alt="${item.gname}">
                        </div>
                        <div>
                            <div class="item-name">${item.gname}</div>
                            <c:if test="${not empty item.gprice}">
                                <div class="item-spec">规格：${item.gprice}</div>
                            </c:if>
                        </div>
                    </div>
                    <div class="item-price">¥<fmt:formatNumber value="${item.gprice}" pattern="#,##0.00"/></div>
                    <div class="item-quantity">
                        <div class="quantity-control">
                            <button class="quantity-btn minus">-</button>
                            <input type="number" class="quantity-input" value=1 min="1">
                            <button class="quantity-btn plus">+</button>
                        </div>
                    </div>
                    <div class="item-subtotal">¥<fmt:formatNumber value="${item.gprice * 1}" pattern="#,##0.00"/></div>
                    <div class="item-action">
                        <a href="${pageContext.request.contextPath}/cart/remove?shopid=${item.shopid}">
                            <span class="delete-btn">删除</span>
                        </a>
                    </div>
                </div>
            </c:forEach>
        </c:when>
        <c:otherwise>
            <div class="empty-cart">
                <img src="${pageContext.request.contextPath}/images/empty-cart.png" alt="空购物车">
                <p>您的购物车还是空的，快去选购商品吧~</p>
            </div>
        </c:otherwise>
    </c:choose>

    <div class="cart-footer">
        <div class="continue-shopping" onclick="window.location.href='${pageContext.request.contextPath}/cart/list'">继续购物</div>
        <div class="total-box">
            <div class="total-info">
                <div>已选择 <span id="selected-count">0</span> 件商品</div>
                <div class="total-amount">合计：¥<span id="total-price">0.00</span></div>
            </div>
            <button id="checkout-btn" class="checkout-btn disabled">去结算</button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化购物车汇总
        updateCartSummary();

        // 全选/取消全选
        document.getElementById('select-all').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.item-check');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            updateCartSummary();
            updateCartItemsSelection();
        });

        // 单个商品选择
        document.querySelectorAll('.item-check').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateCartSummary();
                updateSelectAllStatus();
                updateCartItemsSelection();
            });
        });

        // 数量增减
        document.querySelectorAll('.quantity-btn.minus').forEach(btn => {
            btn.addEventListener('click', function() {
                const input = this.nextElementSibling;
                if (parseInt(input.value) > 1) {
                    input.value = parseInt(input.value) - 1;
                    updateCartItem(this.closest('.cart-item'));
                }
            });
        });

        document.querySelectorAll('.quantity-btn.plus').forEach(btn => {
            btn.addEventListener('click', function() {
                const input = this.previousElementSibling;
                input.value = parseInt(input.value) + 1;
                updateCartItem(this.closest('.cart-item'));
            });
        });

        // 数量输入框
        document.querySelectorAll('.quantity-input').forEach(input => {
            input.addEventListener('change', function() {
                if (parseInt(this.value) < 1) {
                    this.value = 1;
                }
                updateCartItem(this.closest('.cart-item'));
            });
        });

        // 删除商品
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const item = this.closest('.cart-item');
                if (confirm('确定要删除该商品吗？')) {
                    deleteCartItem(item.dataset.id, item);
                }
            });
        });

        // 结算按钮
        document.getElementById('checkout-btn').addEventListener('click', function() {
            if (!this.classList.contains('disabled')) {
                checkout();
            }
        });
    });

    // 更新购物车商品选中状态到服务器
    function updateCartItemsSelection() {
        const selectedItems = [];
        document.querySelectorAll('.cart-item').forEach(item => {
            const checkbox = item.querySelector('.item-check');
            selectedItems.push({
                id: item.dataset.id,
                selected: checkbox.checked
            });
        });

        axios.put('${pageContext.request.contextPath}/api/cart/selection', selectedItems)
            .catch(error => {
                console.error('更新选中状态失败:', error);
            });
    }

    // 更新单个商品信息到服务器
    function updateCartItem(itemElement) {
        const itemId = itemElement.dataset.id;
        const quantity = parseInt(itemElement.querySelector('.quantity-input').value);
        const selected = itemElement.querySelector('.item-check').checked;
        const price = parseFloat(itemElement.querySelector('.item-price').textContent.replace('¥', ''));

        axios.put('${pageContext.request.contextPath}/api/cart/items/' + itemId, {
            quantity: quantity,
            selected: selected
        })
            .then(response => {
                // 更新小计
                itemElement.querySelector('.item-subtotal').textContent =
                    '¥' + (price * quantity).toFixed(2);
                updateCartSummary();
            })
            .catch(error => {
                console.error('更新购物车商品失败:', error);
            });
    }

    // 删除购物车商品
    function deleteCartItem(itemId, itemElement) {
        axios.delete('${pageContext.request.contextPath}/api/cart/items/' + itemId)
            .then(response => {
                itemElement.remove();
                updateCartSummary();
                updateSelectAllStatus();

                // 如果购物车为空，显示空购物车提示
                if (document.querySelectorAll('.cart-item').length === 0) {
                    document.querySelector('.cart-container').innerHTML += `
                            <div class="empty-cart">
                                <img src="${pageContext.request.contextPath}/images/empty-cart.png" alt="空购物车">
                                <p>您的购物车还是空的，快去选购商品吧~</p>
                            </div>
                        `;
                }
            })
            .catch(error => {
                console.error('删除购物车商品失败:', error);
            });
    }

    // 更新购物车汇总信息
    function updateCartSummary() {
        let selectedCount = 0;
        let totalPrice = 0;

        document.querySelectorAll('.cart-item').forEach(item => {
            const checkbox = item.querySelector('.item-check');
            if (checkbox.checked) {
                selectedCount++;
                const price = parseFloat(item.querySelector('.item-price').textContent.replace('¥', ''));
                const quantity = parseInt(item.querySelector('.quantity-input').value);
                totalPrice += price * quantity;
            }
        });

        document.getElementById('selected-count').textContent = selectedCount;
        document.getElementById('total-price').textContent = totalPrice.toFixed(2);

        // 更新结算按钮状态
        const checkoutBtn = document.getElementById('checkout-btn');
        if (selectedCount > 0) {
            checkoutBtn.classList.remove('disabled');
        } else {
            checkoutBtn.classList.add('disabled');
        }
    }

    // 更新全选状态
    function updateSelectAllStatus() {
        const checkboxes = document.querySelectorAll('.item-check');
        const selectAll = document.getElementById('select-all');

        if (checkboxes.length === 0) {
            selectAll.checked = false;
            return;
        }

        const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);
        selectAll.checked = allChecked;
    }

    // 结算功能
    function checkout() {
        const selectedItems = [];
        document.querySelectorAll('.cart-item').forEach(item => {
            const checkbox = item.querySelector('.item-check');
            if (checkbox.checked) {
                selectedItems.push({
                    gid: item.dataset.id,  // 假设这里使用 shopid 作为商品ID
                    quantity: item.querySelector('.quantity-input').value
                });
            }
        });

        if (selectedItems.length === 0) {
            alert('请选择要结算的商品');
            return;
        }

        // 将选中的商品ID和数量作为JSON传递给服务器
        const form = document.createElement('form');
        form.method = 'post';
        form.action = '${pageContext.request.contextPath}/orders/add';

        const itemsInput = document.createElement('input');
        itemsInput.type = 'hidden';
        itemsInput.name = 'cartItems';
        itemsInput.value = JSON.stringify(selectedItems);

        form.appendChild(itemsInput);
        document.body.appendChild(form);
        form.submit();
    }
</script>
</body>
</html>